/**
 * New node file
 */
var dao = require('../dao/dao');
var crypto = require('crypto');

exports.index = function(req, res){
	var output = JSON.stringify(req.cookies);
	
	if(req.cookies.auth === 'true') {
		res.render('index');
	} else {
		res.render('login');
	}
};

var d = new Date();



var id = 'klaus';
var password = '1234';


var s_date = [];
var s_a100 = [];
var s_price = [];
var s_min = 0;
var s_max = 0;
var s_b100 = [];
var s_v100 = [];


var a_date = [];
var a_a100 = [];
var a_a201 = [];
var a_a202 = [];
var a_a203 = [];
var a_a204 = [];
var a_a205 = [];
var a_a206 = [];
var a_a207 = [];
var a_a208 = [];
var a_a209 = [];
var a_a300 = [];
var a_a301 = [];

var b_a100 = [];
var b_a201 = [];
var b_a202 = [];
var b_a203 = [];
var b_a204 = [];
var b_a205 = [];
var b_a206 = [];
var b_a207 = [];
var b_a208 = [];
var b_a209 = [];
var b_a300 = [];
var b_a301 = [];

var v_a100 = [];
var v_a201 = [];
var v_a202 = [];
var v_a203 = [];
var v_a204 = [];
var v_a205 = [];
var v_a206 = [];
var v_a207 = [];
var v_a208 = [];
var v_a209 = [];
var v_a300 = [];
var v_a301 = [];

var min_100 = 0;
var min_201 = 0;
var min_202 = 0;
var min_203 = 0;
var min_204 = 0;
var min_205 = 0;
var min_206 = 0;
var min_207 = 0;
var min_208 = 0;
var min_209 = 0;
var min_300 = 0;
var min_301 = 0;

var max_100 = 0;
var max_201 = 0;
var max_202 = 0;
var max_203 = 0;
var max_204 = 0;
var max_205 = 0;
var max_206 = 0;
var max_207 = 0;
var max_208 = 0;
var max_209 = 0;
var max_300 = 0;
var max_301 = 0;

var ld100 = 0.0;
var ld201 = 0.0;
var ld202 = 0.0;
var ld203 = 0.0;
var ld204 = 0.0;
var ld205 = 0.0;
var ld206 = 0.0;
var ld207 = 0.0;
var ld208 = 0.0;
var ld209 = 0.0;
var ld300 = 0.0;
var ld301 = 0.0;

function init() {
	
	a_date = [];
	a_a100 = [];
	a_a201 = [];
	a_a202 = [];
	a_a203 = [];
	a_a204 = [];
	a_a205 = [];
	a_a206 = [];
	a_a207 = [];
	a_a208 = [];
	a_a209 = [];
	a_a300 = [];
	a_a301 = [];

	b_a100 = [];
	b_a201 = [];
	b_a202 = [];
	b_a203 = [];
	b_a204 = [];
	b_a205 = [];
	b_a206 = [];
	b_a207 = [];
	b_a208 = [];
	b_a209 = [];
	b_a300 = [];
	b_a301 = [];

	v_a100 = [];
	v_a201 = [];
	v_a202 = [];
	v_a203 = [];
	v_a204 = [];
	v_a205 = [];
	v_a206 = [];
	v_a207 = [];
	v_a208 = [];
	v_a209 = [];
	v_a300 = [];
	v_a301 = [];

	min_100 = 0;
	min_201 = 0;
	min_202 = 0;
	min_203 = 0;
	min_204 = 0;
	min_205 = 0;
	min_206 = 0;
	min_207 = 0;
	min_208 = 0;
	min_209 = 0;
	min_300 = 0;
	min_301 = 0;

	max_100 = 0;
	max_201 = 0;
	max_202 = 0;
	max_203 = 0;
	max_204 = 0;
	max_205 = 0;
	max_206 = 0;
	max_207 = 0;
	max_208 = 0;
	max_209 = 0;
	max_300 = 0;
	max_301 = 0;

	ld100 = 0.0;
	ld201 = 0.0;
	ld202 = 0.0;
	ld203 = 0.0;
	ld204 = 0.0;
	ld205 = 0.0;
	ld206 = 0.0;
	ld207 = 0.0;
	ld208 = 0.0;
	ld209 = 0.0;
	ld300 = 0.0;
	ld301 = 0.0;
	
}

function initSupply() {
	
	s_date = [];
	s_a100 = [];
	s_price = [];
	s_min = 0;
	s_max = 0;
	s_b100 = [];
	s_v100 = [];

}

function makeAgentData(rows) {

	initSupply();
	
	console.log( " s_date : " + s_date.length);
	
	// 누적 합계 가공법 
	for (var i = 0; i < rows.length; i++) {
		var row = rows[i];
		s_date[i] = row.stock_date;
		s_price[i] = row.price;
		if (i> 0) {
			s_a100[i] = row.a100 + s_a100[i-1];
		} else {
			s_a100[i] = row.a100;
		}

	}

	s_min = getMinVolum(s_a100);  // 최고저점 가공법;
	s_b100 = getSumHiVolum(s_a100, s_min); // 매집수량  리턴 
	s_max = getMaxVolum(s_b100);				// 매집고점 가공법 
	s_v100 = getVariance(s_b100, s_max);		// 분산비율 


}


function makeData(rows) {
	
	init();
	
	for (var i = 0; i < rows.length; i++) {
	    var row = rows[i];
	    a_date[i] = row.stock_date;
	    if (i> 0) {
		    a_a100[i] = row.a100 + a_a100[i-1];
		    a_a201[i] = row.a201 + a_a201[i-1];
		    a_a202[i] = row.a202 + a_a202[i-1];
		    a_a203[i] = row.a203 + a_a203[i-1];
		    a_a204[i] = row.a204 + a_a204[i-1];
		    a_a205[i] = row.a205 + a_a205[i-1];
		    a_a206[i] = row.a206 + a_a206[i-1];
		    a_a207[i] = row.a207 + a_a207[i-1];
		    a_a208[i] = row.a208 + a_a208[i-1];
		    a_a209[i] = row.a209 + a_a209[i-1];
		    a_a300[i] = row.a300 + a_a300[i-1];
		    a_a301[i] = row.a301 + a_a301[i-1];
	    } else {
	    	a_a100[i] = row.a100;
			a_a201[i] = row.a201;
			a_a202[i] = row.a202;
		    a_a203[i] = row.a203;
		    a_a204[i] = row.a204;
		    a_a205[i] = row.a205;
		    a_a206[i] = row.a206;
		    a_a207[i] = row.a207;
		    a_a208[i] = row.a208;
		    a_a209[i] = row.a209;
		    a_a300[i] = row.a300;
		    a_a301[i] = row.a301;
	    }
	}
	
	min_100 = getMinVolum(a_a100);
	b_a100 = getSumHiVolum(a_a100, min_100);
	
	min_201 = getMinVolum(a_a201);
	b_a201 = getSumHiVolum(a_a201, min_201);
	
	min_202 = getMinVolum(a_a202);
	b_a202 = getSumHiVolum(a_a202, min_202);
	
	min_203 = getMinVolum(a_a203);
	b_a203 = getSumHiVolum(a_a203, min_203);
	
	min_204 = getMinVolum(a_a204);
	b_a204 = getSumHiVolum(a_a204, min_204);
	
	min_205 = getMinVolum(a_a205);
	b_a205 = getSumHiVolum(a_a205, min_205);
	
	min_206 = getMinVolum(a_a206);
	b_a206 = getSumHiVolum(a_a206, min_206);
	
	min_207 = getMinVolum(a_a207);
	b_a207 = getSumHiVolum(a_a207, min_207);
	
	min_208 = getMinVolum(a_a208);
	b_a208 = getSumHiVolum(a_a208, min_208);
	
	min_209 = getMinVolum(a_a209);
	b_a209 = getSumHiVolum(a_a209, min_209);
	
	min_300 = getMinVolum(a_a300);
	b_a300 = getSumHiVolum(a_a300, min_300);

	min_301 = getMinVolum(a_a301);
	b_a301 = getSumHiVolum(a_a301, min_301);
	
}

function getTotal(i) {
	
	return b_a100[i] + b_a201[i] + b_a202[i] + b_a203[i] + b_a204[i] + b_a205[i] + b_a206[i] + b_a207[i] + b_a208[i] + b_a209[i] + b_a300[i] + b_a301[i];
}

//누적 매수량에서 최저매수량 
function getMinVolum(aObj) {
	
	var min = aObj[0];
	for (var i = 0; i < aObj.length; i ++) {
		if( min > aObj[i] ) {
			min = aObj[i];
		}
	}
	
	return min;
}


function getMaxVolum(aObj) {
	var max = aObj[0];
	for (var i = 0; i < aObj.length; i ++) {
		if( aObj[i] > max ) {
			max = aObj[i];
		}
	}
	
	return max;
}

function getVariance(aObj, maxVal) {
	
	var a_tmp = [];
	for(var i=0; i < aObj.length; i++) {
		if(aObj[i] == 0) {
			a_tmp[i] = 0;
		}else {
			a_tmp[i] =  ((aObj[i]/maxVal) * 100).toFixed(2);
		}
	}
	
	return a_tmp;
}


function getSumHiVolum(aObj, minVols){
	var a_tmp = [];
	for(var i=0; i < aObj.length; i++) {
		a_tmp[i] = aObj[i] - minVols;
	}
	
	return a_tmp;
}

function numberWithCommas(x) {
	    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

exports.login = function(req, res){
	
	
	dao.getUserInfo(req.param('name'), function(error,row) {
		
		var pwd = ""; 
		pwd = req.param('password');
		var hash = "";
		hash = crypto.createHash('sha256').update(pwd).digest('base64');		
	
		if(row.length > 0) {
		
			if(req.param('name') === row[0].user_id && hash === row[0].pwd) {
				res.writeHead(302, {
					'Location':'/'
					,'Set-Cookie':['auth=true;expires='+new Date(new Date().getTime()+(1000*3600)).toUTCString()]		// 1000*36000 86409000
				});
				res.end();
			} else {
				res.writeHead(200,{'Content-Type':'text/html'});
				res.end('<h1>Login FAIL</h1>');
			}
		} else {
			res.writeHead(200,{'Content-Type':'text/html'});
			res.end('<h1>Not USER ID </h1>');
		}
	
	});
	
	
};

//exports.login = function(req, res){
//	if(req.param('name') === id && req.param('password') === password) {
//		res.writeHead(302, {
//			'Location':'/'
//				,'Set-Cookie':['auth=true;expires='+new Date(new Date().getTime()+(1000*3600)).toUTCString()]		// 1000*36000 86409000
//		});
//		res.end();
//	} else {
//		res.writeHead(200,{'Content-Type':'text/html'});
//		res.end('<h1>Login FAIL</h1>');
//	}
//	
//};

exports.trad = function(req, res){
	if(req.cookies.auth === 'true') {
		res.render('tradvalue');
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};

exports.org = function(req, res){
	if(req.cookies.auth === 'true') {
		res.render('orgbuylist');
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};

exports.fore = function(req, res){
	if(req.cookies.auth === 'true') {
		res.render('forebuylist');
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};


exports.find = function(req, res){
	if(req.cookies.auth === 'true') {
		res.render('search');
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};

exports.investor = function(req, res){
	if(req.cookies.auth === 'true') {
		dao.getStockInfo(req.body.stock_cd, req.body.stock_date, function(err, rows) {
		
			console.log(err);
			var sday = req.body.stock_date;
			var s_date = sday.substring(0,4) +'.'+ sday.substring(4,6) + '.' + sday.substring(6,8);
			
			res.render('investor', { stock_cd :req.body.stock_cd, stock_date : req.body.stock_date, stock_nm : rows[0].stock_nm,
				closing_price : rows[0].closing_price, contrast : rows[0].contrast, 
				fluctuation_rate : rows[0].fluctuation_rate , trading_volum : rows[0].trading_volum,
				listed_stocks : rows[0].listed_stocks, contvalue : rows[0].contvalue , s_date : s_date, path : req.body.path
			});
		}); 		
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};

exports.stock_search = function(req, res){
	if(req.cookies.auth === 'true') {
			
		res.render('searchlist', {stock_nm : req.body.stock_nm});
		 		
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}	
};

exports.search = function(req, res){
	
//	console.log(req.body.type);
	
	if(req.cookies.auth === 'true') {
		
		if (req.body.type === 'invs') {
		
			dao.getInvestor(req.body.fromDT, req.body.toDT, req.body.stock_cd ,function(err, rows) {
				res.setHeader("Content-Type", "text/json");
				res.setHeader("Access-Control-Allow-Origin", "*");
				res.send(JSON.stringify(rows));
				
			});
			
		} else if (req.body.type === 'trad') {
		
			dao.getTradList(req.body.standDt, req.body.gb, function(err, rows) {
				res.setHeader("Content-Type", "text/json");
				res.setHeader("Access-Control-Allow-Origin", "*");
				res.send(JSON.stringify(rows));
				
			});
		
		} else if (req.body.type === 'srhNm') {
			dao.getStockName(req.body.stock_nm, function(err, rows) {
				res.setHeader("Content-Type", "text/json");
				res.setHeader("Access-Control-Allow-Origin", "*");
				res.send(JSON.stringify(rows));
				
			});
			
		} else if (req.body.type === 'supply') {
			
			dao.getAgentSourceList(req.body.stock_cd, req.body.investor_type ,function(err, rows) {
				
				makeAgentData(rows);
				
				var result = [];
				
				var loop = 0;
				
				if(s_date.length > 40 ) {
					loop = s_date.length - 40;
				} else {
					loop = -1;
				}
				
//				console.log( " a_date :  " +  a_date.length );
				
				for (var i=s_date.length-1; i > loop; i--) {
					
					if(s_price[i] > 0){
					
						var date =  s_date[i].substring(0,4) +'.'+ s_date[i].substring(4,6) + '.' + s_date[i].substring(6,8);
						result.push({
							stock_date : date,
							price: numberWithCommas(s_price[i]),
	//						total_sum : a_a100[i],
	//						min_sum : min_100,
							volum : numberWithCommas(s_b100[i]),
							max_sum : numberWithCommas(s_max),
							val : s_v100[i]
						});
					}
					
				}
				
				res.setHeader("Content-Type", "text/json");
				res.setHeader("Access-Control-Allow-Origin", "*");
				
				res.send(JSON.stringify(result));
				
			});
		}
		
	} else {
		res.render('login');
	}	
};


exports.analysis = function (req, res) {
	
	if(req.cookies.auth === 'true') {	
		
		dao.getSourceList(req.body.stock_cd, function(err, rows) {
			
			makeData(rows);
			var i = a_date.length-1;
			var b_total = getTotal(i);
			ld100 = ((b_a100[i]/b_total) * 100).toFixed(2);
			ld201 = ((b_a201[i]/b_total) * 100).toFixed(2);
			ld202 = ((b_a202[i]/b_total) * 100).toFixed(2);
			ld203 = ((b_a203[i]/b_total) * 100).toFixed(2);
			ld204 = ((b_a204[i]/b_total) * 100).toFixed(2);
			ld205 = ((b_a205[i]/b_total) * 100).toFixed(2);
			ld206 = ((b_a206[i]/b_total) * 100).toFixed(2);
			ld207 = ((b_a207[i]/b_total) * 100).toFixed(2);
			ld208 = ((b_a208[i]/b_total) * 100).toFixed(2);
			ld209 = ((b_a209[i]/b_total) * 100).toFixed(2);
			ld300 = ((b_a300[i]/b_total) * 100).toFixed(2);
			ld301 = ((b_a301[i]/b_total) * 100).toFixed(2);
				
		});
		
		dao.getStockInfo1(req.body.stock_cd, function(err, rows) {
			
			var sday = rows[0].stock_date;
			var s_date = sday.substring(0,4) +'.'+ sday.substring(4,6) + '.' + sday.substring(6,8);
			
			res.render('analysis', { stock_cd :req.body.stock_cd, stock_nm : rows[0].stock_nm,
				closing_price : rows[0].closing_price, contrast : rows[0].contrast, 
				fluctuation_rate : rows[0].fluctuation_rate , trading_volum : rows[0].trading_volum,
				listed_stocks : rows[0].listed_stocks, contvalue : rows[0].contvalue , s_date : s_date,
				ld100 : ld100, ld201 : ld201, ld202 : ld202, ld203 : ld203, ld204 : ld204, ld205 : ld205,
				ld206 : ld206, ld207 : ld207, ld208 : ld208, ld209 : ld209, ld300 : ld300, ld301 : ld301,
				investor_type : req.body.investor_type, path : req.body.path
			});
		}); 	
		
	} else {
		res.writeHead(302, {'Location':'/'});
		res.end();
	}
};




function showList() {
	var result = [];
	for (var i=a_date.length-1; i> a_date.length-21; i--) {
	    result.push( { stock_date: a_date[i],
	        a100: v_a100[i],
	        a201: v_a201[i],
	        a202: v_a202[i],
	        a203: v_a203[i],
	        a204: v_a204[i],
	        a205: v_a205[i],
	        a206: v_a206[i],
	        a207: v_a207[i],
	        a208: v_a208[i],
	        a209: v_a209[i],
	        a300: v_a300[i],
	        a301: v_a301[i] });
	}
	console.log(JSON.stringify(result));
	
}


